/**
 * 
 */
package org.easyelf.springmvc.core.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import org.easyelf.springmvc.core.exception.WebException;
import org.easyelf.springmvc.core.support.security.HttpCode;
import org.easyelf.springmvc.kit.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Title: BaseController
 * @Description: 基础控制类，提供了面向控制层的基础方法
 * @Package: org.easyelf.springmvc.core.base with IntelliJ IDEA
 * @User: RehngaO
 * @Date: 2017-02-07
 * @Time: 下午7:51
 */

public class BaseController {

	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 管理基础路径
	 */
//	@Value("${adminPath}")
	protected String adminPath;

	/**
	 * 前端基础路径
	 */
//	@Value("${frontPath}")
	protected String frontPath;

	/**
	 * 前端URL后缀
	 */
//	@Value("${urlSuffix}")
	protected String urlSuffix;

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	@Autowired
	protected HttpSession session;
	@Autowired
	protected ServletContext application;

	public BaseController() {
	}

	//TODO SpringWind中单点登录
	protected String getCurrentUserId() {
		return this.getSSOToken().getUid();
	}

	protected SSOToken getSSOToken() {
		System.out.println(response);
		SSOToken tk = (SSOToken) SSOHelper.attrToken(this.request);
		if(tk == null) {
			throw new WebException("-1", "The user does not exist, please relogin.");
		} else {
			return tk;
		}
	}

	//TODO kisso中间件
	protected boolean isPost() {
		System.out.println("1");
		return HttpUtil.isPost(this.request);
	}

	protected boolean isGet() {
		return HttpUtil.isGet(this.request);
	}

	protected <T> Page<T> getPage() {
		Integer size = 10;
		return this.getPage(size);
	}

	/**
	 * 传统分页查询
	 * @param pageSize	分页参数，包括pageNum页号、pageSize页行、orderBy排序字段
	 * @return
	 */
	protected <T> Page<T> getPage(int pageSize) {

		int size = pageSize;
		int current = 1;
		if(this.request.getParameter("pageNum") != null) {
			current = Integer.parseInt(this.request.getParameter("pageNum"));
		}
		if(this.request.getParameter("pageSize") != null) {
			size = Integer.parseInt(this.request.getParameter("pageSize"));
		}
		if (size == -1) {
			return new Page();
		}
		Page<T> page = new Page(current, size);
		page.setAsc(false);
		return page;
	}

	protected String redirectTo(String url) {
		StringBuffer rto = new StringBuffer("redirect:");
		rto.append(url);
		return rto.toString();
	}

	protected String toJson(Object object) {
		return JSON.toJSONString(object, new SerializerFeature[]{SerializerFeature.BrowserCompatible});
	}

	protected String toJson(Object object, String format) {
		return format == null?this.toJson(object):JSON.toJSONStringWithDateFormat(object, format, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat});
	}

	/**
	 * 渲染失败数据
	 *
	 * @return result
	 */
	protected JsonResult renderError() {
		JsonResult result = new JsonResult();
		result.setSuccess(false);
		result.setCode(HttpCode.INTERNAL_SERVER_ERROR.value());
		return result;
	}

	/**
	 * 渲染失败数据（带消息）
	 *
	 * @param msg 需要返回的消息
	 * @return result
	 */
	protected JsonResult renderError(String msg) {
		JsonResult result = renderError();
		result.setMessage(msg);
		return result;
	}

	/**
	 * 渲染成功数据
	 *
	 * @return result
	 */
	protected JsonResult renderSuccess() {
		JsonResult result = new JsonResult();
		result.setSuccess(true);
		result.setCode(HttpCode.OK.value());
		return result;
	}

	/**
	 * 渲染成功数据（带信息）
	 *
	 * @param msg 需要返回的信息
	 * @return result
	 */
	protected JsonResult renderSuccess(String msg) {
		JsonResult result = renderSuccess();
		result.setMessage(msg);
		return result;
	}

	/**
	 * 渲染成功数据（带数据）
	 *
	 * @param object 需要返回的对象
	 * @return result
	 */
	protected JsonResult renderSuccess(Object object) {
		JsonResult result = renderSuccess();
		result.setObject(object);
		return result;
	}

	/**
	 * 转换为 bootstrap-table 需要的分页格式 JSON
	 * @param list
	 * @return
	 */
	protected JSONObject renderPage(List<?> list) {
		//用PageInfo对结果进行包装
		PageInfo page = new PageInfo(list);
		//测试PageInfo全部属性
		//PageInfo包含了非常全面的分页属性
//		assertEquals(1, page.getPageNum());
//		assertEquals(10, page.getPageSize());
//		assertEquals(1, page.getStartRow());
//		assertEquals(10, page.getEndRow());
//		assertEquals(183, page.getTotal());
//		assertEquals(19, page.getPages());
//		assertEquals(1, page.getFirstPage());
//		assertEquals(8, page.getLastPage());
//		assertEquals(true, page.isFirstPage());
//		assertEquals(false, page.isLastPage());
//		assertEquals(false, page.isHasPreviousPage());
//		assertEquals(true, page.isHasNextPage());
		JSONObject json = new JSONObject();
		json.put("total", page.getTotal());
		json.put("rows", list);
		return json;
	}

//	/** 设置成功响应代码 */
//	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
//		return setSuccessModelMap(modelMap, null);
//	}
//
//	/** 设置成功响应代码 */
//	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
//		return setModelMap(modelMap, HttpCode.OK, data);
//	}
//
//	/** 设置响应代码 */
//	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
//		return setModelMap(modelMap, code, null);
//	}
//
//
//	/** 设置响应代码 */
//	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
//		Map<String, Object> map = new LinkedHashMap<String, Object>();//TODO InstanceUtil.newLinkedHashMap();
//		map.putAll(modelMap);
//		modelMap.clear();
//		for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
//			String key = iterator.next();
//			if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) {
//				modelMap.put(key, map.get(key));
//			}
//		}
//		if (data != null) {
//			if (data instanceof Page) {
//				Page<?> page = (Page<?>) data;
//				modelMap.put("data", page.getRecords());
//				modelMap.put("current", page.getCurrent());
//				modelMap.put("size", page.getSize());
//				modelMap.put("pages", page.getPages());
//				modelMap.put("total", page.getTotal());
//				modelMap.put("iTotalRecords", page.getTotal());
//				modelMap.put("iTotalDisplayRecords", page.getTotal());
//			} else if (data instanceof List<?>) {
//				modelMap.put("data", data);
//				modelMap.put("iTotalRecords", ((List<?>) data).size());
//				modelMap.put("iTotalDisplayRecords", ((List<?>) data).size());
//			} else {
//				modelMap.put("data", data);
//			}
//		}
//		modelMap.put("httpCode", code.value());
//		modelMap.put("msg", code.msg());
//		modelMap.put("timestamp", System.currentTimeMillis());
//		return ResponseEntity.ok(modelMap);
//	}
//
//	/** 异常处理 */
//	@ExceptionHandler(Exception.class)
//	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
//			throws Exception {
//		logger.error(Constants.Exception_Head, ex);
//		ModelMap modelMap = new ModelMap();
//		if (ex instanceof BaseException) {
//			((BaseException) ex).handler(modelMap);
//		} else if (ex instanceof IllegalArgumentException) {
//			new IllegalParameterException(ex.getMessage()).handler(modelMap);
////		} else if (ex instanceof UnauthorizedException) {
////			modelMap.put("httpCode", HttpCode.FORBIDDEN.value());
////			modelMap.put("msg", StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.FORBIDDEN.msg()));
//		} else {
//			modelMap.put("httpCode", HttpCode.INTERNAL_SERVER_ERROR.value());
//			String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg());
//			modelMap.put("msg", msg.length() > 100 ? "系统走神了,请稍候再试." : msg);
//		}
//		response.setContentType("application/json;charset=UTF-8");
//		modelMap.put("timestamp", System.currentTimeMillis());
//		logger.info(JSON.toJSON(modelMap));
//		byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
//		response.getOutputStream().write(bytes);
//	}
}
